#include "mainwindow.h"

using namespace pj;
using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->MainWindowUiInit();
    this->PJSUA2_Init();
    printInfoClass = new print_info;
}

MainWindow::~MainWindow()
{
    delete acc;
    ep->libDestroy();
    delete myLog;
    delete printInfoClass;
    delete ep;
    delete ui;
}

void MainWindow::PJSUA2_Init(void)
{
    pj_log_set_level(6);
    ep = new Endpoint;

    try {//创建库
        ep->libCreate();
    } catch(Error& err) {
        qDebug() << "Startup error:" << err.info().c_str();
    }

    try {//初始化和配置库
        EpConfig ep_cfg;
        // Specify customization of settings in ep_cfg
        ep->libInit(ep_cfg);
        ep_cfg.logConfig.level = 5;
        ep_cfg.uaConfig.maxCalls = 4;
        ep_cfg.medConfig.sndClockRate = 16000;
    } catch(Error& err) {
        qDebug() << "Initialization error:" << err.info().c_str();
    }

    try {//创建一个或多个传输
        TransportConfig tcfg;
        tcfg.port = TransPort;
        TransportId pid = ep->transportCreate(PJSIP_TRANSPORT_UDP, tcfg);
        defaultTransportId = pid;
    } catch(Error& err) {
        qDebug() << "Transport creation error: " << err.info().c_str() << endl;
    }

    try {
        ep->libStart();
    } catch(Error& err) {
        qDebug()  << "Startup error: " << err.info().c_str() << endl;
    }
}

void MainWindow::MainWindowUiInit(void)
{
#if (QTDEMO_NUM == 1)
    TransPort = SIP_PORT_1;
    selfURL =   SELF_URI_1;
    destURL =   DEST_URI_1;
    usrName =   USR_NAME_1;
#elif (QTDEMO_NUM == 2)
    TransPort = SIP_PORT_2;
    selfURL =   SELF_URI_2;
    destURL =   DEST_URI_2;
    usrName =   USR_NAME_2;
#endif
    ui->lineEdit_SlefUrl->setText(selfURL);
    ui->lineEdit_destUrl->setText(destURL);
    ui->lineEdit_changePort->setText(QString::number(TransPort));
    ui->pushButton_answer->setEnabled(false);

    // 注册 OnInstantMessageParam 类型
    qRegisterMetaType<OnInstantMessageParam>("OnInstantMessageParam");
    qRegisterMetaType<OnIncomingCallParam>("OnIncomingCallParam");

    acc  = nullptr;
    ep   = nullptr;
    this->setWindowTitle("qtdemo"+QString::number(QTDEMO_NUM));

    myLog = new Log(this);
    myLog->installMessageHandler();
}

void MainWindow::FunctionDemo1(void)
{

}

void MainWindow::CleanUIAnswer(void)
{
    qDebug()<<"CleanUIAnswer going";
    ui->pushButton_answer->setStyleSheet("");
    ui->pushButton_answer->setEnabled(false);
}

void MainWindow::IncomingCallSolt(OnIncomingCallParam* iprm)
{
    ui->pushButton_answer->setStyleSheet("background-color: green; color: white;");
    ui->pushButton_answer->setEnabled(true);

    ui->label_incomingCallUrl->setText(QString::fromStdString(iprm->rdata.srcAddress));
}

void MainWindow::OnCallStateOverSolt(void)
{
    qDebug()<<"OnCallStateOverSolt going";

    ui->label_OnThePhoneUrl->setText("");
    if(CheckAccIsExist())
    {
        acc->cleanExistCall();
    }
}

void MainWindow::OnCallMediaStateSolt(void)
{
    string remoteUrl;
    qDebug()<<"OnCallMediaStateSolt going";

    remoteUrl = acc->getRemoteUrl();

    if(remoteUrl == "error")
    {
        qDebug()<<"no url can print.";
    }
    else
    {
        ui->label_OnThePhoneUrl->setText(QString::fromStdString(remoteUrl));
        ui->label_incomingCallUrl->setText("");
    }
}

void MainWindow::OnInstantMessageSolt(OnInstantMessageParam* prm)
{
    qDebug()<<"OnInstantMessageSolt going";
    QString printMessage = QString::fromStdString(prm->fromUri)+":"+QString::fromStdString(prm->msgBody);
    ui->textEdit_mesg->append(printMessage);
    cout<<prm->fromUri;
    qDebug()<<printMessage;
}

void MainWindow::CleanUITakingCall(void)
{
    ui->label_OnThePhoneUrl->setText("");
}

bool MainWindow::CheckAccIsExist(void)
{
    if(acc == nullptr)
    {
        qDebug()<<"You don't have a account.Please create a account.";
        return false;
    }
    else if(!acc->isValid())
    {
        qDebug()<<"Your account isn't valid.";
        return false;
    }
    else
    {
        return true;
    }
}


/*on_pushButton function *********************************************************************************************************************************/

void MainWindow::on_pushButton_createAccount_clicked()
{
    qDebug()<<"on_pushButton_createAccount_clicked";
    AccountConfig acc_cfg;
    AccountInfo accountInfo;
    string selfUrl = ui->lineEdit_SlefUrl->text().toStdString();
    acc_cfg.idUri = selfUrl;

#if(FS_REGISTER_SWITCH == 1)
    acc_cfg.regConfig.registrarUri = FS_URI;
    AuthCredInfo credInfo;
    credInfo.realm = "*";
    credInfo.username = usrName;
    credInfo.dataType = 0;
    credInfo.data     = "1234";
    acc_cfg.sipConfig.authCreds.push_back(credInfo);
#endif

    if (acc == nullptr) {
        acc = new My_account(this);
        // Create the account
        try {
            acc->create(acc_cfg);
            accountInfo = acc->getInfo();
            //连接通话的信号与槽
            connect(acc,&My_account::EOnCallStateOverChange,this,&MainWindow::OnCallStateOverSolt);
            connect(acc,&My_account::EOnCallMediaStateChange,this,&MainWindow::OnCallMediaStateSolt);
            connect(acc,&My_account::EOnInstantMessageChange,this,&MainWindow::OnInstantMessageSolt);
            connect(acc,&My_account::incomingCallSignal,this,&MainWindow::IncomingCallSolt);
        } catch(Error& err) {
            std::cout << "Account creation error: " << err.info() << std::endl;
        }
    } else {
        // Modify the account
        try {
            //Update the registration
            acc->modify(acc_cfg);
            acc->setRegistration(true);
            accountInfo = acc->getInfo();
        } catch(Error& err) {
            std::cout << "Account modify error: " << err.info() << std::endl;
        }
    }

    printInfoClass->printAccountInfo(accountInfo);
}

void MainWindow::on_pushButton_call_clicked()
{
    AccountInfo accountInfo;
    qDebug()<<"on_pushButton_createAccount_clicked";
    string destUrl = ui->lineEdit_destUrl->text().toStdString();
    if(CheckAccIsExist())
    {
        acc->UseRemoteUrlMakeACall(destUrl);
    }
}

void MainWindow::on_pushButton_changePort_clicked()
{
    qDebug()<<"on_pushButton_changePort_clicked";
    TransportConfig tcfg;
    tcfg.port = ui->lineEdit_changePort->text().toInt();
    if(tcfg.port == static_cast<unsigned int>(TransPort))
    {
        qDebug()<<"Transport is exist.";
        return;
    }
    ep->transportClose(defaultTransportId);
    try {//创建一个或多个传输
        TransportId pid = ep->transportCreate(PJSIP_TRANSPORT_UDP, tcfg);
        defaultTransportId = pid;
        TransPort = tcfg.port;
        qDebug()<<"Transport change success port="<<TransPort;
    } catch(Error& err) {
        qDebug() << "Transport creation error: " << err.info().c_str() << endl;
    }
}

void MainWindow::on_pushButton_config1_clicked()
{
    TransPort = SIP_PORT_1;
    selfURL = SELF_URI_1;
    destURL = DEST_URI_1;

    ui->lineEdit_SlefUrl->setText(selfURL);
    ui->lineEdit_destUrl->setText(destURL);
    ui->lineEdit_changePort->setText(QString::number(TransPort));
}

void MainWindow::on_pushButton_config2_clicked()
{
    TransPort = SIP_PORT_2;
    selfURL = SELF_URI_2;
    destURL = DEST_URI_2;

    ui->lineEdit_SlefUrl->setText(selfURL);
    ui->lineEdit_destUrl->setText(destURL);
    ui->lineEdit_changePort->setText(QString::number(TransPort));
}

void MainWindow::on_pushButton_close_clicked()
{
    this->close();
}

void MainWindow::on_pushButton_hanup_clicked()
{
    if(CheckAccIsExist())
    {
        acc->hangUpCall();
    }
}

void MainWindow::on_pushButton_shutDown_clicked()
{
    if(CheckAccIsExist())
    {
        acc->shutdown();
        acc = nullptr;
    }
}

void MainWindow::on_pushButton_hold_clicked()
{
    static bool holdState = false;
    CallOpParam prm;

    if(holdState == false)
    {
        if(acc->HoldCall())
        {
            holdState = true;
            ui->pushButton_hold->setText("reinvite");
        }
    }
    else
    {
        if(acc->ReinviteCall())
        {
            holdState = false;
            ui->pushButton_hold->setText("hold");
        }
    }
}

void MainWindow::on_pushButton_configWin_clicked()
{
    destURL = DEST_URI_WIN;

    ui->lineEdit_destUrl->setText(destURL);
}

void MainWindow::on_pushButton_sendMsg_clicked()
{
    SendInstantMessageParam prm;
    prm.content = ui->lineEdit_sendMsg->text().toStdString();

    if(CheckAccIsExist())
    {
        acc->sendInstantMessageToRemote(ui->lineEdit_sendMsg->text().toStdString());
    }
}


void MainWindow::on_pushButton_answer_clicked()
{
    if(CheckAccIsExist())
    {
        acc->answerReceiveCall();
        this->CleanUIAnswer();  //清除answer按键的内容
    }
}

void MainWindow::on_pushButton_playWav_clicked()
{
    if(CheckAccIsExist())
    {
        acc->startPlayWavToRemote();
    }
}

void MainWindow::on_pushButton_stopWav_clicked()
{
    if(CheckAccIsExist())
    {
        acc->stopPlayWavToRemote();
    }
}
